package main

import (
	"flag"
	"fmt"
	"gateway/core"
	"github.com/go-resty/resty/v2"
	"github.com/jedib0t/go-pretty/v6/table"
	"github.com/zh-five/xdaemon"
	"log"
	"net/http"
)

func main() {
	run := flag.Bool("run", false, "启动网关")
	//输出服务列表
	ps := flag.String("ps", "", "输出服务列表")
	//是否开发环境
	dev := flag.Bool("dev", false, "开发环境")
	//监听端口号
	flag.StringVar(&core.HttpPort, "hp", "9307", "http监听服务端口号")
	flag.Parse()
	if ps != nil && *ps != "" {
		printPs(*ps)
		return
	}
	if *run {
		//后台启动
		daemon(*dev)
		//输出日志
		log.Println("Http Server Port:", core.HttpPort)
		//设置秘钥
		log.Println("secret: ", core.Secret)
		//启动端口服务
		http.ListenAndServe(":"+core.HttpPort, nil)
	}
}

// printPs
//
//	@Description: 输出注册的服务
func printPs(ps string) {
	t := table.NewWriter()
	header := table.Row{"name", "ip", "port", "server", "weight", "volume"}
	t.AppendHeader(header)
	mp := make(map[string]core.LoadBalance)
	req := resty.New().R().SetResult(&mp).ForceContentType("application/json")
	req.Header.Set("secret", core.Secret)
	req.Get("http://127.0.0.1:" + core.HttpPort + "/admin/api?key=" + ps)
	for _, lb := range mp {
		for _, server := range lb.Servers {
			row := table.Row{server.Name, server.Host, server.Port, server.Prefix, server.Weight, server.Volume}
			t.AppendRow(row)
		}
	}
	fmt.Println(t.Render())
}

// daemon
//
//	@Description: 后台启动
//	@param dev
func daemon(dev bool) {
	if dev {
		return
	}
	xdaemon.Background(core.LogFile, true)
}
